import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { PointsGoodsExchangeEntity, PointsGoodsExchangeStatus } from './points-goods-exchange.entity';
import { Repository } from 'typeorm';
import { FindPointsGoodsExchangeListDto, PointsGoodsExchangePageDto, PointsGoodsExchangeExportDto } from './points-goods-exchange.dto';
import { StandardPagination, standardPaginate } from '~/helper/paginate';

@Injectable()
export class PointsGoodsExchangeService {
  constructor(
    @InjectRepository(PointsGoodsExchangeEntity)
    private readonly pointsGoodsExchangeRepo: Repository<PointsGoodsExchangeEntity>
  ) {}

  async create(userId: number, goodsId: number, dto: Partial<PointsGoodsExchangeEntity>) {
    return await this.pointsGoodsExchangeRepo.save({
      ...dto,
      user: { id: userId },
      goods: { id: goodsId },
    });
  }

  async getExchangeByList({
    page,
    pageSize,
    userId,
  }: FindPointsGoodsExchangeListDto & { userId: number }): Promise<
    StandardPagination<PointsGoodsExchangeEntity>
  > {
    const queryBuilder = this.pointsGoodsExchangeRepo
      .createQueryBuilder('ah_points_goods_exchange')
      .select([
        'ah_points_goods_exchange.id',
        'ah_points_goods_exchange.createdAt',
        'ah_points_goods_exchange.updatedAt',
      ])
      .where('ah_points_goods_exchange.user = :userId', { userId })
      .orderBy('ah_points_goods_exchange.createdAt', 'DESC');

    return standardPaginate(queryBuilder, {
      page,
      pageSize,
    });
  }

  /**
   * 分页查询积分商品兑换列表
   * @param dto 分页查询参数
   * @returns 分页结果
   */
  async findPage(dto: PointsGoodsExchangePageDto): Promise<StandardPagination<PointsGoodsExchangeEntity>> {
    const queryBuilder = this.pointsGoodsExchangeRepo
      .createQueryBuilder('exchange')
      .leftJoinAndSelect('exchange.goods', 'goods')
      .leftJoinAndSelect('exchange.user', 'user')
      .leftJoinAndSelect('user.wechat', 'wechat')
      .select([
        'exchange.id',
        'exchange.title',
        'exchange.imageUrl',
        'exchange.status',
        'exchange.createdAt',
        'exchange.updatedAt',
        'goods.name',
        'goods.price',
        'goods.image',
        'goods.description',
        'user.id',
        'wechat.nickname',
        'wechat.phone',
        'wechat.avatar',
      ])
      .orderBy('exchange.createdAt', 'DESC');

    // 根据兑换状态筛选
    if (dto.status) {
      queryBuilder.andWhere('exchange.status = :status', { status: dto.status });
    }

    // 根据兑换标题模糊查询
    if (dto.title) {
      queryBuilder.andWhere('exchange.title LIKE :title', { title: `%${dto.title}%` });
    }

    // 根据用户ID筛选
    if (dto.userId) {
      queryBuilder.andWhere('exchange.user.id = :userId', { userId: dto.userId });
    }

    // 根据商品ID筛选
    if (dto.goodsId) {
      queryBuilder.andWhere('exchange.goods.id = :goodsId', { goodsId: dto.goodsId });
    }

    return standardPaginate(queryBuilder, { page: dto.page, pageSize: dto.pageSize });
  }

  /**
   * 查询所有积分商品兑换数据用于导出
   * @param dto 查询参数
   * @returns 所有符合条件的兑换记录
   */
  async findAllForExport(dto: PointsGoodsExchangeExportDto): Promise<PointsGoodsExchangeEntity[]> {
    const queryBuilder = this.pointsGoodsExchangeRepo
      .createQueryBuilder('exchange')
      .leftJoinAndSelect('exchange.goods', 'goods')
      .leftJoinAndSelect('exchange.user', 'user')
      .leftJoinAndSelect('user.wechat', 'wechat')
      .leftJoinAndSelect('user.admin', 'admin')
      .select([
        'exchange.id',
        'exchange.title',
        'exchange.imageUrl',
        'exchange.status',
        'exchange.createdAt',
        'exchange.updatedAt',
        'goods.name',
        'goods.price',
        'goods.image',
        'goods.description',
        'user.id',
        'wechat.nickname',
        'wechat.phone',
        'wechat.avatar',
        'admin.username',
      ])
      .orderBy('exchange.createdAt', 'DESC');

    // 根据兑换状态筛选
    if (dto.status) {
      queryBuilder.andWhere('exchange.status = :status', { status: dto.status });
    }

    // 根据兑换标题模糊查询
    if (dto.title) {
      queryBuilder.andWhere('exchange.title LIKE :title', { title: `%${dto.title}%` });
    }

    // 根据用户ID筛选
    if (dto.userId) {
      queryBuilder.andWhere('exchange.user.id = :userId', { userId: dto.userId });
    }

    // 根据商品ID筛选
    if (dto.goodsId) {
      queryBuilder.andWhere('exchange.goods.id = :goodsId', { goodsId: dto.goodsId });
    }

    return await queryBuilder.getMany();
  }

  /**
   * 更新积分商品兑换状态
   * @param id 兑换记录ID
   * @param status 更新的状态
   * @returns 更新后的兑换记录
   */
  async updateStatus(id: number, status: PointsGoodsExchangeStatus): Promise<void> {
    const exchange = await this.pointsGoodsExchangeRepo.findOne({
      where: { id },
      relations: ['goods', 'user', 'user.wechat'],
    });

    if (!exchange) {
      throw new NotFoundException(`ID为${id}的积分商品兑换记录不存在`);
    }

    await this.pointsGoodsExchangeRepo.update(id, { status });
  }
}
